package com.action.app;

import java.io.PrintWriter;
import java.util.Date;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;
import org.json.JSONObject;

import com.enetiy.Area;
import com.enetiy.Areaip;
import com.enetiy.Areaitemip;
import com.enetiy.Push;
import com.operation.GateIP;
import com.operation.HttpSendUrl;
import com.operation.SendMC;
import com.service.AreaIpService;
import com.service.AreaService;
import com.util.DataUtil;
import com.util.IPUtil;
import com.util.Log4gUtil;

public class GateAction {
	
	private String localIp;
	private int siteAreaid;
	private AreaIpService areaIpService;
	private AreaService areaService;
	
	private String keyword;
	private String service;
	private int iden;
	private String projectName;
	/**
	 * 存储或修改区域公网IP地址
	 */
	public void	getGateIp(){
		
		System.out.println("&&&&&&&&&&&&&&&&&&");
		
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpServletRequest request = ServletActionContext.getRequest();
		String ip = GateIP.getIP(request);
		Log4gUtil.getLog().info("区域--:"+siteAreaid+" -公网IP地址--:"+ip);
		PrintWriter out = null;
		String ji = "0";
		try {
			out = response.getWriter();
			Area area = areaService.selectArea(siteAreaid);
			if(area!=null){
				Areaip areaip = areaIpService.selectAreaip(siteAreaid);
				if(areaip==null){
					areaip=new Areaip();
					areaip.setArea(area);
					if(siteAreaid==1)
						areaip.getIschange();
					else
						areaip.setIschange(1);
					areaip.setTime(new Date());
					areaip.setPublicIp(ip);
					areaIpService.insertAreaIp(areaip);
				}else{
					areaip.setTime(new Date());
					if(areaip.getIschange()!=0)
						areaip.setPublicIp(ip);
					areaIpService.updateAreaIp(areaip);
					ji = "1";
				}
			}
		} catch (Exception e) {
			ji = "-1";
			e.printStackTrace();
		}
		out.print(ji);
	}
	/**
	 * 新增或修改项目心跳 >Nf050
	 */
	public void projectBounce(){
		try {
			//区域id是否合法
			Area selectArea = areaService.selectArea(siteAreaid);
			if(selectArea!=null&&keyword!=null&&!keyword.equals("")){
				Areaitemip areaitemip = areaIpService.selectAreaitemip(keyword, siteAreaid);
				if(areaitemip!=null){//存在即修改
					areaitemip.setUpdateTime(new Date());
					areaitemip.setService(service);
					areaitemip.setIden(iden);
					areaitemip.setProjectName(projectName);
					areaitemip.setIp(localIp);
					areaIpService.updateAreaitemip(areaitemip);
				}else{//不存在即新增
					areaitemip =new Areaitemip(selectArea, keyword,projectName,new Date(), localIp, service, iden );
					areaIpService.insertAreaitemip(areaitemip);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}
	/**
	 * 检查心跳
	 */
	public void inspectBounce(){
		if(!IPUtil.getHeartOpen().equals("false")){
			System.out.println("进入检查心跳inspectBounce");
			 final Integer cacheTime = 1000 *60 *10; //十分钟 
		        Timer timer = new Timer();  
		        // (TimerTask task, long delay, long period)任务，延迟时间，多久执行  
		        timer.schedule(new TimerTask() {  
		            @Override  
		            public void run() {  
						try {
							//全部心跳项目
						//	List<Areaitemip> list = areaIpService.selectAreaitemipList();
							//全部区域代理
							List<Areaip> areaipList = areaIpService.selectAreaipList();
							long newTime = new Date().getTime();//现在时间
							/*if(!list.isEmpty()){
			            		//1.检查心跳项目
			            		for (int i = 0; i < list.size(); i++) {
			            			Areaitemip areaitem = list.get(i);
			            			long updatetime = areaitem.getUpdateTime().getTime();//项目报告时间
			            			//心跳项目失联
									if((updatetime+cacheTime)<newTime){
										if(areaitem.getIden()==0){
											//项目失联 提醒操作.........
											//推送用户
											List<Push> pushList = areaIpService.selectPushList("心跳", 1);
											String reason ="";
											if(!pushList.isEmpty()){
												for (int j = 0; j < pushList.size(); j++) {
														reason = SendMC.getSendSingle(pushList.get(j).getPushAccount(), "999999");
													Thread.sleep(20000);
												}
												if(reason.equals("0")){
													areaitem.setIden(1);
													areaIpService.updateAreaitemip(areaitem);
												}
											}
										}
										Log4gUtil.getLog().info("项目失联提醒: -区域:"+areaitem.getArea().getAreaName()
												+"--"+areaitem.getService()+"服务器-"+areaitem.getProjectName()+"项目 已失联");
									}
			            		}
			            	}*/
			            	
			            	if(!areaipList.isEmpty()){
			            		//2.检查代理服务,和公网地址
			            		for (int i = 0; i < areaipList.size(); i++) {
			            			boolean qflg= false;
			            			long updatetime = areaipList.get(i).getTime().getTime();//项目报告时间
			            			HttpSendUrl send  = new  HttpSendUrl();
			            			/*String url ="http://"+areaipList.get(i).getPublicIp()+areaipList.get(i).getHeartUrl();
			            			String ru = "1";
			            			String Gate = "";
			            			int count = 0;
			            			do {
				            			try {
				            				if(areaipList.get(i).getHeartUrl()!=null&&!areaipList.get(i).getHeartUrl().contains("(no)"))
				            					ru = send.getSendRequest(url, "", "GET",5000);
				            				JSONObject dataParser = DataUtil.dataParser(ru);
				            				dataParser.has("Gate");
				            					Gate = dataParser.getString("Gate");
				            			} catch (Exception e) {
				            				Gate = "-1";
				    						e.printStackTrace();
				    					}
				            			//公网地址失联并可提醒
				            			if(!Gate.equals("Gate")){
				            				if(areaipList.get(i).getIden()==0){
				            					qflg=true;
				            				}
				            				Log4gUtil.getLog().info("项目失联提醒: -区域:"+areaipList.get(i).getArea().getAreaName()
				            						+"--代理服务器-公网地址 已失联");
				            				Thread.sleep(32000);//如失联睡眠32秒
				            			}
				            			count++;
			            			} while (qflg&&count<3);//3次失联
*/			            			//代理项目失联
			            			if((updatetime+cacheTime)<newTime){
			            				if(areaipList.get(i).getIden()==0){
			            					qflg = true;
										}
										Log4gUtil.getLog().info("项目失联提醒: -区域:"+areaipList.get(i).getArea().getAreaName()
												+"--代理服务器- 已失联");
			            			}
			            			
			            			//发送短信项目失联提醒..
			            			if(qflg){
			            				//推送用户
										List<Push> pushList = areaIpService.selectPushList("心跳", 1);
										String reason ="";
										if(!pushList.isEmpty()){
											for (int j = 0; j < pushList.size(); j++) {
												reason = SendMC.getSendSingle(pushList.get(j).getPushAccount(), "999999");
												Thread.sleep(20000);
											}
										if(reason.equals("0")){
											areaipList.get(i).setIden(1);
											areaIpService.updateAreaIp(areaipList.get(i));
										}
			            			}
								}
			            	}
			            }
						} catch (Exception e) {
							e.printStackTrace();
						}
		            }  
		        },5000, cacheTime);//5秒后启动 , 每cacheTime分钟检查
			}
	}
	
	
	
	/**
	 * 网络验证接口  >Nf014
	 */
	public void	getAreaIp(){
		HttpServletRequest request = ServletActionContext.getRequest();
		String ip = GateIP.getIP(request);
		Log4gUtil.getLog().info("getAreaIp-app区域验证-siteAreaid:"+siteAreaid+"-公网IP地址:"+ip);
		net.sf.json.JSONObject sendJson = DataUtil.sendJson();
		HttpServletResponse response = ServletActionContext.getResponse();
		PrintWriter out = null;
		try {
			out = response.getWriter();
			Areaip areaIp = areaIpService.selectAreaIp(ip);
			if(siteAreaid==0){
				if(areaIp!=null){
					sendJson.put("code", 1);
					sendJson.put("agencyIp",areaIp.getAgencyIp());
				}else{
					sendJson.put("code", 0);
				}
			}else{
				Areaip areaip = areaIpService.selectAreaip(siteAreaid);
				if(areaip!=null){
					sendJson.put("code", 1);
					sendJson.put("agencyIp",areaip.getAgencyIp());
				}else{
					sendJson.put("code",0);
				}
			}
		} catch (Exception e) {
			sendJson.put("code", -1);
			e.printStackTrace();
		}
		out.print(sendJson);	
	}
	
	

	

	public void setLocalIp(String localIp) {
		this.localIp = localIp;
	}
	public void setAreaIpService(AreaIpService areaIpService) {
		this.areaIpService = areaIpService;
	}
	public void setSiteAreaid(int siteAreaid) {
		this.siteAreaid = siteAreaid;
	}

	public void setAreaService(AreaService areaService) {
		this.areaService = areaService;
	}
	public void setKeyword(String keyword) {
		this.keyword = keyword;
	}
	public void setService(String service) {
		this.service = service;
	}
	public void setIden(int iden) {
		this.iden = iden;
	}
	public void setProjectName(String projectName) {
		this.projectName = projectName;
	}
	
}
